<template>
  <view class="filter-model">
    <view class="model-content" @click="showFuc">
      <view class="imgBox">
        <image src="@/static/images/index/selectA.png" mode="" v-if="Object.keys(choosed).length || (dateOpt && dateOpt.startTime !== '') || (dateOpt && dateOpt.planBeginDate !== '')
          "></image>
        <image src="@/static/images/index/selectD.png" mode="" v-else></image>
      </view>
      <view class="model-content-title" :style="{
        color:
          Object.keys(choosed).length || (dateOpt && dateOpt.startTime !== '') || (dateOpt && dateOpt.planBeginDate !== '')
            ? '#0091ff'
            : '#333',
      }">{{ "筛选" }}</view>
    </view>

    <filter-drawer :chooseData="choosed" :filterList="filterList" :comfireText="comfireText" :show="showFilter"
      :keyMap="keyMap" :orderType="orderType" :title="['保养历史筛选', '维修历史筛选', '配件历史筛选','事务历史筛选','质检历史筛选','救援历史筛选'][orderType]" ref="filter-drawer"
      :isShowTemplate="orderType == 0 ? true : false" :isShowPart="orderType == 2 ? true : false" :isShowDate="true"
      @closed="handleClose" @submit="submitFilter" @chooseTag="getResultCount"></filter-drawer>
    <time-select v-if="selectTimePopup" :beforeToday="false" :atterToday="true" :isChooseToday="true"
      @close="closeSelectTimePopup"></time-select>
  </view>
</template>

<script>
import { getNowTime } from '@/utils/utils.js';
import timeSelect from '@/pages/index/components/timeSelect.vue';
import filterDrawer from '@/components/filter-drawer/filterDrawer.vue';
import { timeLiness, duration, signType } from '@/apis/workOrder.js';
import {
	maintenanceHistoryTasks,
	repairHistoryTasks,
	partHistoryTasks,
} from '@/apis/elevator.js';
import { problemItem, getPart } from '@/apis/barrierSearch.js';
// import { getElevatorList } from '@/apis/barrierSearch.js';
import { removeEmpty } from '@/utils/utils.js';
import {getUserlistPlan } from '@/apis/workOrder.js';
export default {
	name: 'filter-model',
	components: { filterDrawer, timeSelect },
	props: {
		disabled: {
			type: Boolean,
			default: false,
		},
		all: {
			type: Boolean,
			default: true,
		},
		csd: {
			type: Object,
			default: () => {
				return {};
			},
		},
		userIds: {
			type: String,
			default: '',
		},
		orderType: {
			type: Number,
		},
		elevatorId: {
			type: String,
		},
		dateOpt: {
			type: Object,
		},
	},
	data() {
		return {
			selectTimePopup: false,
			filterList: [],
			choosed: {},
			showFilter: false,
			allChecked: true,
			chooseArr: [], // 选中的标签arr
			comfireText: '确定',
			keyMap: {},
			startTime: '',
			isShowTemplate: true,
			dateObj: {
				startTime: '',
				endTime: '',
				value: '',
				planBeginDate: '',
				planEndDate: ''
			},
			mList: [
				{
					key: 'timeliness',
					title: '及时性',
					list: [
						{ name: '及时', value: 1 },
						{ name: '超时', value: 2 },
					],
				},
				{
					title: '逾期情况',
					key: 'overdue',
					list: [
						{
							name: '已逾期',
							value: '2'
						},
						{
							name: '未逾期',
							value: '1'
						}
					]
				},
				{
					title: '任务时长',
					key: 'duration',
					list: [
						{ name: '正常', value: 1 },
						{ name: '时间过长', value: 2 },
						{ name: '时间过短', value: 3 },
					],
				},
				{
					title: '签到签退',
					key: 'sign',
					list: [
						{ name: '正常', value: 1 },
						{ name: '签到定位异常', value: 2 },
						{ name: '签退定位异常', value: 3 },
						{ name: '系统代签', value: 4 },
					],
				},
			],
			wList: [
				{
					title: '报障状态',
					key: 'elevatorStop',
					list: [
						{ name: '停梯', value: 2 },
						{ name: '正常', value: 1 },
					],
				},
				{
					title: '签到签退',
					key: 'sign',
					list: [
						{ name: '正常', value: 1 },
						{ name: '签到定位异常', value: 2 },
						{ name: '签退定位异常', value: 3 },
						{ name: '系统签退', value: 4 },
					],
				},
			],
			pjList: [
				{
					title: '签到签退',
					key: 'sign',
					list: [
						{ name: '正常', value: 1 },
						{ name: '签到定位异常', value: 2 },
						{ name: '签退定位异常', value: 3 },
						{ name: '系统签退', value: 4 },
					],
				},
			],
			optionKey: '',
			problemList: [],
		};
	},
	async created() {
		// this.initModel();
		this.allChecked = this.all;
		this.choosed = this.csd;
		// 给日期组件赋值

		setTimeout(() => {
			this.setChooseArr();
		}, 500);
		this.getAllItem();
		uni.$on('getCustomerSwitch', (data, key) => {
			this.selectTimePopup = data;
			this.optionKey = key;
		});
	},
	beforeDestroy() {
		uni.$off('getCustomerSwitch');
	},
	computed: {
		showConditions() {
			// console.log(this.choosed,this.csd,666)
			let flag = false;
			flag =
        this.allChecked || Object.keys(this.choosed).length === 0
        	? true
        	: false;
			return flag;
		},
	},
	watch: {
		showFilter(val) {
			console.log('showFilter',val);
			this.$emit('showFilterChange', val);
		},
	},
	methods: {
		// 自定义日期
		closeSelectTimePopup(res) {
			let start = '',startR = '';
			let end = '',endR = '';
			if (res) {
				if (res.indexOf('-') != -1) {
					const timeArr = res.split('-');
					start = timeArr[0].replaceAll('.', '-');
					end = timeArr[1].replaceAll('.', '-');
					startR = timeArr[0].replaceAll('.', '/');
					endR = timeArr[1].replaceAll('.', '/');
				} else {
					const time = res.replaceAll('.', '-');
					const timeR = res.replaceAll('.', '/');
					start = time;
					end = time;
					startR = timeR;
					endR = timeR;
				}
				const nowDay = getNowTime().replaceAll('-', '/');
				let nowtime = new Date(nowDay).getTime();
				let starttime = new Date(startR).getTime();
				let endtime = new Date(endR).getTime();
				console.log('自定义日期', res,nowDay,startR,endR);

				if (endtime >= nowtime && !this.beforeToday && !this.isChooseToday) {
					console.log('包含今天');
					uni.showToast({
						title: '自定义日期范围须小于今天',
						icon: 'none',
					});
					return;
				}
			} else {
			}
			this.selectTimePopup = false;
			uni.$emit('closeTimeSelect', { start, end, optionKey: this.optionKey });
		},
		getAllItem() {
			problemItem({}).then((res) => {
				if (res) {
					this.problemList = res.data;
				}
			});
		},
		reset() {
			this.$refs['filter-drawer'].handleReset();
		},
		async initModel(index) {
			// console.log(index,"初始化")
			let all = [];
			this.filterList = [];
			if (index == 0) {
				// all = [timeLiness(), duration(), signType()];
				// await Promise.all(all).then(res => {
				// 	if(res){
				// 		let taskMap={
				// 			0:{
				// 				title:'及时性',
				// 				key:'timeliness'
				// 			},
				// 			1:{
				// 				title:'任务时长',
				// 				key:'duration'
				// 			},
				// 			2:{
				// 				title:'签到签退',
				// 				key:'sign'
				// 			}
				// 		}

				// 		let arr=res.map((item,i)=>{
				// 			let list=[]
				// 			item.data.map(e=>{
				// 				list.push({name:e.name,value:e.value})
				// 			})

				// 			return{
				// 				title:taskMap[i].title,
				// 				key:taskMap[i].key,
				// 				list,
				// 			}
				// 		})
				// 		this.filterList=arr
				// 		this.setKeyMap(this.filterList);
				// 		// console.log(this.filterList,'保养')

				// 	}
				// })
				this.filterList = this.mList;
				this.setKeyMap(this.filterList);
			} else if (index == 1) {
				let arr = this.problemList.map((e) => {
					return {
						name: e.dictValue,
						value: e.dictKey,
					};
				});

				let list = [
					{
						title: '报障状态',
						key: 'elevatorStop',
						list: [
							{ name: '停梯', value: 2 },
							{ name: '正常', value: 1 },
						],
					},
				];
				this.filterList = [
					...list,
					{ title: '故障现象', key: 'problemItems', list: arr },
					{
						title: '签到签退',
						key: 'sign',
						list: [
							{ name: '正常', value: 1 },
							{ name: '签到定位异常', value: 2 },
							{ name: '签退定位异常', value: 3 },
							{ name: '系统签退', value: 4 },
						],
					},
				];
				this.setKeyMap(this.filterList);
			} else if ([3,4].includes(index)) {
				this.filterList = [{
					title: '签到签退', key: 'sign',
					list: [{ name: '正常', value: 1 }, { name: '签到定位异常', value: 2 }, { name: '签退定位异常', value: 3 }, { name: '系统签退', value: 4 }]
				}];
				this.setKeyMap(this.filterList);
			} else if (index === 5) {
				this.filterList = [];
			} else {
				// console.log('这里是配件');
				this.filterList = [
					{
						title: '签到签退',
						key: 'sign',
						list: [
							{ name: '正常', value: 1 },
							{ name: '签到定位异常', value: 2 },
							{ name: '签退定位异常', value: 3 },
							{ name: '系统签退', value: 4 },
						],
					},
				];
				this.setKeyMap(this.filterList);
			}
			this.choosed = this.csd;
			this.dateObj = this.dateOpt;
		},
		// 关闭操作
		handleClose() {
			this.showFilter = false;
			console.log(this.showFilter, 'eason');
			let obj = {};
			this.chooseArr.forEach((item) => {
				if (obj[item.key]) {
					obj[item.key].push(item.value);
				} else {
					obj[item.key] = [];
					obj[item.key].push(item.value);
				}
			});
			this.choosed = obj;

			// 日期父组件接受日期默认值

			this.$nextTick(() => {
				this.$refs['filter-drawer'].initData(obj, this.dateOpt);
			});
		},
		// 打开对话框
		showFuc() {
			if (this.disabled) {
				return;
			}

			setTimeout(() => {
				this.showFilter = true;
				// 初始化组组件
				let obj = {
					allChecked: this.allChecked,
					choosed: this.choosed,
					...this.dateOpt,
				};
				this.$refs['filter-drawer'].initData(this.choosed, this.dateOpt);
				this.handleCount(obj);
			}, 500);
		},
		// 完成筛选
		filterd(res) {
			let obj = JSON.parse(JSON.stringify(res.dateObj));
			if (obj.startTime && obj.startTime.indexOf(':') == -1) {
				obj.startTime = obj.startTime + ' 00:00:00';
			}
			if (obj.endTime && obj.endTime.indexOf(':') == -1) {
				obj.endTime = obj.endTime + ' 23:59:59';
			}

			if (obj.planBeginDate && obj.planBeginDate.indexOf(':') == -1) {
				obj.planBeginDate = obj.planBeginDate + ' 00:00:00';
			}
			if (obj.planEndDate && obj.planEndDate.indexOf(':') == -1) {
				obj.planEndDate = obj.planEndDate + ' 23:59:59';
			}
			this.$emit('filterd', {
				choosed: this.choosed,
				allChecked: this.allChecked,
				dateObj: obj,
			});
		},
		// 接受父组件保存按钮的操作
		submitFilter(res) {
			this.keyMap = res.keyMap;
			// console.log(this.keyMap, 222);
			this.allChecked = res.allChecked;
			this.choosed = res.choosed;
			this.showFilter = false;
			this.setChooseArr();
			this.filterd(res);
		},

		// 删除筛选item
		removeItem(item, index) {
			// console.log(222);
			// this.showFilter=true
			this.showFuc();
			return;
		},

		// 渲染已选标签
		setChooseArr() {
			let filterList = this.filterList;
			if (this.allChecked) {
				this.chooseArr = [];
				return;
			}
			let arr = [];
			for (let key in this.choosed) {
				let obj = this.filterList.find((item, i) => {
					return item.key === key;
				});
				console.log(obj, 'obj的值set的值');
				if (obj) {
					obj.list.forEach((e) => {
						if (this.choosed[key].indexOf(e.value) != -1) {
							arr.push({
								...e,
								key,
							});
						}
					});
				}
			}

			this.chooseArr = arr;
			// console.log(this.chooseArr, 'this.chooseArr');
		},

		setKeyMap(list) {
			const map = new Map();
			list.forEach((item) => {
				map.set(item.key, { flag: false });
			});
			const obj = [...map.entries()].reduce(
				(obj, [key, value]) => ((obj[key] = value), obj),
				{}
			);
			// console.log(obj, 'flagMap');
			this.keyMap = obj;
		},
		// 获取条数
		// handlegetElevatorList(obj) {
		// 	return new Promise((resolve, reject) => {
		// 		getElevatorList(obj)
		// 			.then(res => {
		// 				if (res) {
		// 					resolve(res.data);
		// 				}
		// 			})
		// 			.catch(() => {
		// 				resolve({});
		// 			});
		// 	});
		// },
		getListTotal(obj) {
			uni.showLoading({
				title: '加载中',
				icon: 'none',
			});
			return new Promise((resolve, reject) => {
				let typeQueryArr = [
					maintenanceHistoryTasks,
					repairHistoryTasks,
					partHistoryTasks,
					getUserlistPlan,
				];
				let tindex = [3,4,5].includes(this.orderType) ? 3 : this.orderType;
				typeQueryArr[tindex](obj)
					.then((res) => {
						if (res) {
							uni.hideLoading();
							resolve(res.data);
						}
					})
					.catch(() => {
						resolve({});
					});
			});
		},
		// 点击标签的时候
		getResultCount(res) {
			// console.log(res,'切换重置');
			this.startTime = res.startTime;
			this.choosed = res.choosed;
			this.handleCount(res);
		},
		// 获取点击筛选条件后的数量总数
		async handleCount(res) {
			let obj = JSON.parse(JSON.stringify(res));
			if (obj.startTime && obj.startTime.indexOf(':') == -1) {
				obj.startTime = obj.startTime + ' 00:00:00';
			}
			if (obj.endTime && obj.endTime.indexOf(':') == -1) {
				obj.endTime = obj.endTime + ' 23:59:59';
			}

			if (obj.planBeginDate && obj.planBeginDate.indexOf(':') == -1) {
				obj.planBeginDate = obj.planBeginDate + ' 00:00:00';
			}
			if (obj.planEndDate && obj.planEndDate.indexOf(':') == -1) {
				obj.planEndDate = obj.planEndDate + ' 23:59:59';
			}
			console.log(res, '这里是计算');
			const { allChecked, choosed, startTime, endTime, planBeginDate, planEndDate } = obj;

			// if (!allChecked && !Object.keys(choosed).length && !startTime) {
			// 	this.comfireText = '确定';
			// 	return;
			// }
			let params = {
				elevatorId: this.elevatorId,
				startTime,
				endTime,
				planBeginDate,
				planEndDate,
			};
			let query = {};
			// if (Object.keys(choosed).length || allChecked||startTime!==null) {
			if (Object.keys(choosed).length) {
				const map = new Map();

				for (let key in choosed) {
					map.set(key, choosed[key]);
				}
				const obj = [...map.entries()].reduce((obj, [key, value]) => (
					(obj[key] = value.join(',')), obj
				), {});

				query = obj;
			}
			if ([3,4,5].includes(this.orderType)) {
				params.typeStatus = [5,6,7][this.orderType - 3];
				params.planStatus = 4; // 任务状态为已完成
				if (planBeginDate && planEndDate) {
					params.createBeginTime =  planBeginDate; 
					params.createEndTime =  planEndDate;
				}
				if (startTime && endTime) {
					params.finishBeginTime =  startTime; 
					params.finishEndTime =  endTime;
				}
			}

			for (const key in query) {
				if (query[key] == '') {
					delete query[key];
				}
			}
			const tempList = ['startTime', 'endTime', 'elevatorId', 'planBeginDate', 'planEndDate','createBeginTime','createEndTime','finishBeginTime','finishEndTime','typeStatus','planStatus'];
			let tempParams = Object.keys(choosed).length
				? { ...query, ...params }
				: params;
			for (let key in tempParams) {
				if (!tempList.includes(key)) {
					tempParams[key] = tempParams[key].split(',');
				}
			}

			// 获取请求的数据
			let count = await this.getListTotal(tempParams);

			// console.log(count.total,"数值");
			if (count.total > 0) {
				this.comfireText = `查看${count.total}条数据`;
			} else {
				uni.showToast({
					icon: 'none',
					title: '筛选结果为空 请重新选择条件',
				});
				this.comfireText = '完成';
			}
			// }
		},
	},
};
</script>

<style lang="scss" scoped>
.filter-model {
  width: 100%;
  display: flex;
  justify-content: flex-end;

  .imgBox {
    display: flex;

    image {
      width: 32rpx;
      height: 32rpx;
    }
  }

  .model-content {
    width: calc(100% - 40rpx);
    // padding: 0 20rpx;`
    display: flex;
    font-size: 26rpx;
    color: #333;
    // padding-bottom: 20rpx;
    align-items: center;
    justify-content: flex-end;

    &-title {
      display: flex;
      // font-weight: bold;
      letter-spacing: 1rpx;
      align-items: center;
      margin-right: 10rpx;

      image {
        width: 22rpx;
        height: 22rpx;
        transition: 0.3s all;
        margin: 4rpx 0rpx 0 7rpx;
      }

      .line {
        width: 2rpx;
        height: 30rpx;
        background-color: #ccc;
        margin-left: 12rpx;
      }
    }

    &-all {
      font-size: 24rpx;
      color: #999;
      margin-left: 12rpx;
    }

    &-tags {
      flex: 1;
      display: flex;
      flex-wrap: wrap;

      &-item {
        border: 2rpx solid #cccccc;
        padding: 0 4rpx 2rpx 8rpx;
        color: #666;
        border-radius: 4rpx;
        margin: 10rpx;
        font-size: 24rpx;

        image {
          width: 20rpx;
          height: 20rpx;
        }
      }
    }
  }
}
</style>
